<template>
  <div class="dashboard-container">
    <el-card class="welcome-card">
      <div class="welcome-header">
        <div class="welcome-info">
          <h2>欢迎，{{ userInfo.username }}</h2>
          <p>{{ userInfo.companyName || '' }}</p>
          <p>{{ getCurrentDate() }}</p>
        </div>
        <div class="welcome-actions">
          <el-button type="primary" icon="el-icon-s-order" @click="goToOrderManagement">订单管理</el-button>
          <el-button type="success" icon="el-icon-s-promotion" @click="goToLogistics">物流管理</el-button>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-card-header">
            <i class="el-icon-shopping-cart-full stat-icon"></i>
            <div class="stat-info">
              <div class="stat-label">总订单</div>
              <div class="stat-value">{{ stats.totalOrders }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-card-header">
            <i class="el-icon-s-order stat-icon orange"></i>
            <div class="stat-info">
              <div class="stat-label">待处理订单</div>
              <div class="stat-value">{{ stats.pendingOrders }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-card-header">
            <i class="el-icon-truck stat-icon blue"></i>
            <div class="stat-info">
              <div class="stat-label">配送中</div>
              <div class="stat-value">{{ stats.shippingOrders }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-card-header">
            <i class="el-icon-user stat-icon purple"></i>
            <div class="stat-info">
              <div class="stat-label">客户数量</div>
              <div class="stat-value">{{ stats.customerCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="clearfix">
              <span>销售趋势</span>
              <el-radio-group v-model="salesPeriod" size="small" style="float: right" @change="fetchSalesData">
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
                <el-radio-button label="year">年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div id="sales-chart" style="height: 350px"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="order-card">
          <template #header>
            <div class="clearfix">
              <span>最近订单</span>
              <el-button style="float: right" type="text" @click="goToOrderManagement">查看全部</el-button>
            </div>
          </template>
          <el-table :data="recentOrders" style="width: 100%" v-loading="ordersLoading">
            <el-table-column prop="orderNo" label="订单号" width="120"></el-table-column>
            <el-table-column prop="productName" label="产品名称"></el-table-column>
            <el-table-column prop="customerName" label="客户" width="120"></el-table-column>
            <el-table-column prop="orderDate" label="订单日期" width="120"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.statusText }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>
// 引入API
import { userAPI, statisticsAPI } from '@/api/api';
// 引入图表
import * as echarts from 'echarts';

export default {
  name: 'DealerDashboardPageView',
  data() {
    return {
      userInfo: {},
      salesPeriod: 'week',
      stats: {
        totalOrders: 0,
        pendingOrders: 0,
        shippingOrders: 0,
        customerCount: 0
      },
      salesChart: null,
      salesData: [],
      salesLabels: [],
      recentOrders: [],
      todoTasks: [],
      ordersLoading: false
    }
  },
  created() {
    this.getUserInfo();
  },
  mounted() {
    this.fetchDashboardData();
  },
  methods: {
    // 获取所有数据
    async fetchDashboardData() {
      this.fetchStats();
      this.fetchSalesData();
      this.fetchRecentOrders();
      this.fetchTodoTasks();
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await userAPI.getUserInfo();
        this.userInfo = response.data;
      } catch (error) {
        console.error('Failed to fetch user info:', error);
        this.$message.error('获取用户信息失败');
      }
    },

    // 获取统计数据
    async fetchStats() {
      try {
        const response = await statisticsAPI.getDealerStats();
        this.stats = response.data;
      } catch (error) {
        console.error('Failed to fetch stats:', error);
        this.$message.error('获取统计数据失败');
      }
    },

    // 获取销售趋势数据
    async fetchSalesData() {
      try {
        const response = await statisticsAPI.getDealerSalesData(this.salesPeriod);
        this.salesData = response.data.values;
        this.salesLabels = response.data.labels;
        this.$nextTick(() => {
          this.initSalesChart();
        });
      } catch (error) {
        console.error('Failed to fetch sales data:', error);
        this.$message.error('获取销售趋势数据失败');
      }
    },

    // 获取最近订单数据
    async fetchRecentOrders() {
      try {
        this.ordersLoading = true;
        const response = await statisticsAPI.getRecentOrders();
        if (response.success && response.data) {
          // 处理返回的数据
          this.recentOrders = response.data.map(order => {
            return {
              ...order,
              statusText: this.getStatusText(order.status)
            };
          });
        } else {
          console.warn('获取最近订单数据失败:', response.message);
          this.recentOrders = [];
        }
      } catch (error) {
        console.error('Failed to fetch recent orders:', error);
        this.$message.error('获取最近订单数据失败');
        this.recentOrders = [];
      } finally {
        this.ordersLoading = false;
      }
    },

    // 获取待办任务
    async fetchTodoTasks() {
      try {
        // 获取当前用户ID
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        const dealerId = userInfo.id;

        if (!dealerId) {
          console.warn('没有找到经销商ID，无法获取待办任务');
          return;
        }

        const response = await statisticsAPI.getDealerTodoTasks(dealerId);
        if (response.success && response.data) {
          this.todoTasks = response.data;
        } else {
          console.warn('获取待办任务失败:', response.message);
          this.todoTasks = [];
        }
      } catch (error) {
        console.error('Failed to fetch todo tasks:', error);
        this.$message.error('获取待办任务失败');
        this.todoTasks = [];
      }
    },

    // 初始化销售趋势图表
    initSalesChart() {
      if (this.salesChart) {
        this.salesChart.dispose();
      }

      this.salesChart = echarts.init(document.getElementById('sales-chart'));

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.salesLabels
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '销售额',
            type: 'line',
            stack: 'Total',
            data: this.salesData,
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#409EFF'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(64, 158, 255, 0.7)'
                },
                {
                  offset: 1,
                  color: 'rgba(64, 158, 255, 0.1)'
                }
              ])
            }
          }
        ]
      };

      this.salesChart.setOption(option);

      window.addEventListener('resize', this.resizeSalesChart);
    },

    resizeSalesChart() {
      if (this.salesChart) {
        this.salesChart.resize();
      }
    },

    // 获取当前日期
    getCurrentDate() {
      const date = new Date();
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
    },

    // 跳转到订单管理
    goToOrderManagement() {
      this.$router.push('/dealer/order-management');
    },

    // 跳转到物流管理
    goToLogistics() {
      this.$router.push('/dealer/logistics-management');
    },

    // 获取状态类型
    getStatusType(status) {
      const typeMap = {
        'PENDING': 'warning',
        'PROCESSING': 'primary',
        'SHIPPED': 'info',
        'DELIVERED': 'success',
        'CANCELED': 'danger'
      };
      return typeMap[status] || '';
    },

    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        'PENDING': '待处理',
        'PROCESSING': '处理中',
        'SHIPPED': '已发货',
        'DELIVERED': '已送达',
        'CANCELED': '已取消'
      };
      return textMap[status] || '未知状态';
    },

    // 获取任务优先级颜色
    getTaskColor(priority) {
      const colorMap = {
        'high': '#F56C6C',
        'medium': '#E6A23C',
        'low': '#67C23A'
      };
      return colorMap[priority] || '';
    }
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.resizeSalesChart);
    if (this.salesChart) {
      this.salesChart.dispose();
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.welcome-card {
  margin-bottom: 20px;
}

.welcome-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-info h2 {
  margin: 0 0 5px 0;
  font-size: 22px;
}

.welcome-info p {
  margin: 5px 0;
  color: #606266;
}

.welcome-actions {
  display: flex;
  gap: 10px;
}

.stat-card {
  height: 100px;
  margin-bottom: 20px;
}

.stat-card-header {
  display: flex;
  align-items: center;
}

.stat-icon {
  font-size: 40px;
  margin-right: 15px;
  color: #67C23A;
}

.stat-icon.orange {
  color: #E6A23C;
}

.stat-icon.blue {
  color: #409EFF;
}

.stat-icon.purple {
  color: #909399;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-card {
  margin-bottom: 20px;
  height: 400px;
}

.order-card {
  margin-bottom: 20px;
}

.todo-card {
  margin-bottom: 20px;
  height: 400px;
  overflow-y: auto;
}
</style>
